package com.hnust.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hnust.entity.Alarm;
import com.hnust.entity.Device;
import com.hnust.entity.dto.AlarmDto;
import com.hnust.entity.dto.DeviceDto;
import com.hnust.mapper.AlarmMapper;
import com.hnust.service.AlarmService;
import com.hnust.service.DeviceService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 创建人：zhangRuWang
 * 创建时间：2022/5/5
 * 描述：
 */
@Service
public class AlarmServiceImpl extends ServiceImpl<AlarmMapper, Alarm> implements AlarmService {

    @Autowired
    private DeviceService deviceService;

    @Override
    public Page<AlarmDto> alarmSearch(int page, int pageSize, String beginTime, String endTime) {
        Page<Alarm> alarmPage=new Page<>(page,pageSize);
        Page<AlarmDto> alarmDtoPage=new Page<>(page,pageSize);
        this.page(alarmPage,new QueryWrapper<Alarm>()
        .apply(beginTime!=null&&!beginTime.equals(""),"date_format (update_time,'%Y-%m-%d %H:%i:%s') >= date_format('"
                + beginTime+ "','%Y-%m-%d %H:%i:%s')")
        .apply(endTime!=null&&!endTime.equals(""),"date_format (update_time,'%Y-%m-%d %H:%i:%s') <= date_format('"
                + endTime+ "','%Y-%m-%d %H:%i:%s')")
        .orderByDesc("update_time"));
        BeanUtils.copyProperties(alarmPage,alarmDtoPage,"records");
        List<Alarm> alarmList=alarmPage.getRecords();
        List<AlarmDto> alarmDtoList=alarmList.stream().map((item)->{
            AlarmDto alarmDto=new AlarmDto();
            this.alarmToDto(alarmDto,item);
            return alarmDto;
        }).collect(Collectors.toList());
        alarmDtoPage.setRecords(alarmDtoList);
        return alarmDtoPage;
    }

    public void alarmToDto(AlarmDto alarmDto,Alarm alarm){
        BeanUtils.copyProperties(alarm,alarmDto);
        Device d=deviceService.getById(alarm.getDeviceId());
        DeviceDto deviceDto=new DeviceDto();
        deviceService.deviceToDto(deviceDto,d);
        alarmDto.setDeviceDto(deviceDto);
        alarmDto.setDealWithName(alarm.getDealWith()==1?"已处理":"未处理");
    }
}
